import React, {Component} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { connect, history } from 'umi'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons'
import {
  Button,
  Card,
  Input,
  Select,
  Row,
  Col,
  Table,
  message,
  Drawer,
} from 'antd'

import DetailList from './component/DetailList'

const { Option } = Select;

class Index extends Component {

  state = {
    searchType: 'productName', // 搜索类型
    searchName: '', // 搜索关键字
    pageNum: 1, // 当前第1页
    pageSize: 3, // 每页3条
    total: 0, // 总条数
    isUpdateAdd: false, // 是否修改添加,进而控制pageNum, pageSize
    products:  [], // 商品列表初始化
    showStatus: 0, // 0: drawer隐藏, 1: 详情drawer显示, 1: 修改drawer显示
  }

  extra = (
    <Button
      onClick={
        () =>{
          const { dispatch } = this.props
          const { pageNum, pageSize } = this.state
          this.setState({ isUpdateAdd: true})
          history.push('/products/addUpdate')
          dispatch({
            type: 'product/save',
            payload: {
              product: {},
              isUpdate: false,
              addupdatePageNum: pageNum,
              addupdatePageSize: pageSize,
            }
          })
        }
       }
      type="primary"
    ><PlusOutlined />添加</Button>
  )

  columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price}`
    },
    {
      title: '状态',
      // dataIndex: 'status',
      key: 'status',
      width: '15%',
      render: (product) => {
        const { status, _id } = product
        const newStatus = status === 1 ? 2: 1
        return (
          <div>
            <Button onClick={() => this.updataProductStatus(_id, newStatus)} type="primary">{status === 1 ? '上架' : '下架'}</Button>
            <span>{ status === 1 ? '已下架' : '在售'}</span>
          </div>
        )
      }
    },
    {
      title: '操作',
      key: 'actions',
      width: '15%',
      render: (product) => (
        <div>
          <Button onClick={() => this.showDetail(product)} type="link">详情</Button>
          <Button
            onClick={
              () => {
                const { dispatch } = this.props
                const { pageNum, pageSize, searchName } = this.state
                this.setState({ isUpdateAdd: true})
                history.push('/products/addUpdate')
                dispatch({
                  type: 'product/save',
                  payload: {
                    product,
                    isUpdate: true,
                    addupdatePageNum: pageNum,
                    addupdatePageSize: pageSize,
                    searchName
                  }
                })
              }
            }
            type="link"
          >修改</Button>
        </div>
      )
    },
  ];

  updataProductStatus = (productId, status) => {
    const { dispatch } = this.props
    const { pageNum, pageSize } = this.state
    dispatch({
      type: 'product/fetchUpdateStatus',
      payload: {productId, status},
      callback: (result) => {
        const { msg } = result
        if (result.status === 0) {
         message.success(`商品${status === 1 ? '下架' : '上架'}成功!`)
          this.getProducts(pageNum, pageSize)
        }else {
          message.error(msg)
        }
      }
    })
  }

  // 获取指定页码的列表数据显示
  getProducts = (pageNum , pageSize) => {
    const { dispatch } = this.props
    const { searchType, searchName } = this.state
    let result
    if (searchName) {
      // 搜索关键字存在时, 进行搜索分页
      dispatch({
        type: 'product/fetchSearchProducts',
        payload: {pageNum, pageSize, searchType, searchName},
        callback: (data) => {
          result = data
          const { status, data: { total, list }, msg} = result
          if (status === 0) {
            this.setState({
              products: list,
              total
            })
          }else {
            message.error(msg)
          }
        }
      })
    }else {
      // 一般分页请求
      dispatch({
        type: 'product/fetchProducts',
        payload: {pageNum, pageSize},
        callback: (data) => {
          result = data
          const { status, data: { total, list }, msg} = result
          if (status === 0) {
            this.setState({
              products: list,
              total
            })
          }else {
            message.error(msg)
          }
        }
      })
    }

    this.setState({
      pageNum,
      pageSize
    })
  };

  // 搜索重置
  reset = () => {
    this.setState({searchName: '', productsStatus: false }, () => {
      this.getProducts(1, 3)
    })
  };

  onClose = () => {
    this.setState({showStatus: 0})
  };

  // 查看详情抽屉
  showDetail = (product) => {
    const { dispatch } = this.props
    this.setState({
      showStatus: 1,
    })
    dispatch({
      type: 'product/save',
      payload: {
        productDetail: product,
      }
    })
  };

  componentDidMount(): void {
    const { addupdatePageNum, addupdatePageSize } = this.props
    this.getProducts(addupdatePageNum, addupdatePageSize)
  }

  render() {
    const { searchType, searchName, products , total, showStatus, isUpdateAdd, pageNum, pageSize } = this.state
    const { isLoading, addupdatePageNum, addupdatePageSize } = this.props

    const title = (
      <Row gutter={20}>
        <Col md={2} sm={4}>
          <Select value={searchType} onChange={value => this.setState({searchType: value})}>
            <Option value="productName">按名称搜索</Option>
            <Option value="productDesc">按描述搜索</Option>
          </Select>
        </Col >

        <Col md={2} sm={4}>
          <Input value={searchName} onChange={e => this.setState({searchName: e.target.value})} placeholder="关键字"/>
        </Col>

        <Col md={2} sm={4}>
          <Button
            onClick={() => {
              this.setState({
                productsStatus: true,
                pageNum: 1,
                pageSize: 3
              }, () => {
                const { pageNum, pageSize } = this.state
                this.getProducts(pageNum, pageSize)
              })
            }}
            type="primary" htmlType="submit"
          >
            <SearchOutlined />搜索
          </Button>
        </Col>
        <Col md={1} sm={2}>
          <Button onClick={this.reset} type="primary" htmlType="submit">
            重置
          </Button>
        </Col>
      </Row>
    )
    return (
      <PageContainer>
        <Card title={title} extra={this.extra}>
          <Table
            bordered
            rowKey="_id"
            loading={isLoading}
            dataSource={products}
            columns={this.columns}
            pagination={{
              current:  isUpdateAdd ? addupdatePageNum: pageNum,
              pageSize: isUpdateAdd ? addupdatePageSize: pageSize,
              total,
              showQuickJumper:  true,
              showSizeChanger:  true,
              pageSizeOptions: ['3', '5', '7', '10'],
              onChange: (pageNum, pageSize) => {
                this.getProducts(pageNum, pageSize)
              },
              showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条数据`
            }}
          />
          <Drawer
            title="商品详情"
            width={720}
            onClose={this.onClose}
            visible={showStatus === 1}
            bodyStyle={{ paddingBottom: 80 }}
          >
            <DetailList/>
          </Drawer>
        </Card>
      </PageContainer>
    );
  }
}

export default connect(({product, loading}) => ({
  ...product,
  isLoading: loading.effects['product/fetchProducts'],
}))(Index);
